﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace EcoSystem
{
    /// <summary>
    /// 
    /// </summary>
    public class EnumHelper
    {
        private static Dictionary<Type, List<EnumItemInfo>> allEnums = new Dictionary<Type, List<EnumItemInfo>>();

        /// <summary>
        /// 获取枚举名称、值及描述列表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static List<EnumItemInfo> GetEnums(Type type)
        {
            if (allEnums.ContainsKey(type))
            {
                return allEnums[type];
            }

            List<EnumItemInfo> list = new List<EnumItemInfo>();
            foreach (var emName in Enum.GetNames(type))
            {
                var value = Enum.Parse(type, emName);
                var descriptoin = GetEnumAtribute(value);
                list.Add(new EnumItemInfo()
                {
                    Descrption = descriptoin,
                    Name = emName,
                    Value = (int)value
                });
            }
            allEnums.Add(type, list);
            return list;
        }

        /// <summary>
        /// 获取枚举值自定义属性描述字段字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetEnumAtribute(object obj)
        {
            if (obj == null)
                return string.Empty;
            FieldInfo field = obj.GetType().GetField(obj.ToString());
            var attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault() as DescriptionAttribute;
            if (attribute != null)
            {
                return attribute.Description;
            }
            return obj.ToString();
        }

    }
}
